// src/api/system/aichat.js

export function startChatSSE(msg, onData, onError, onComplete) {
  if (!msg) throw new Error('消息不能为空')

  const url = `/api/aichat/chat?msg=${encodeURIComponent(msg)}`
  const eventSource = new EventSource(url)

  eventSource.onmessage = (event) => {
    onData && onData(event.data)
  }

  eventSource.onerror = (event) => {
    onError && onError(event)
    eventSource.close()
    onComplete && onComplete()
  }

  // 返回关闭连接的函数，方便外部主动调用
  return () => {
    eventSource.close()
    onComplete && onComplete()
  }
}
